<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #div1 {
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: #f00;
    }
  </style>
</head>
<body>
  <div id="div1"></div>
  <script>
    var oDiv = document.getElementById("div1")
    oDiv.onmousedown = function(ev) {
      var e = ev || window.event
      var offsetX = e.clientX - oDiv.offsetLeft
      var offsetY = e.clientY - oDiv.offsetTop
      document.onmousemove = function(ev) {
        var e = ev || window.event
        var l = e.clientX - offsetX
        var t = e.clientY - offsetY
        if (l <= 0) {
          l = 0
        }
        if (t <= 0) {
          t = 0
        }
        var windowWidth = document.documentElement.clientWidth
        var windowHeight = document.documentElement.clientHeight
        if (l >= windowWidth - oDiv.offsetWidth) {
          l = windowWidth - oDiv.offsetWidth
        }
        if (t >= windowHeight - oDiv.offsetHeight - 1) {
          t = windowHeight - oDiv.offsetHeight - 1
        }

        oDiv.style.left = l + "px"
        oDiv.style.top = t + "px"
      }
    }
    document.onmouseup = function() {
      document.onmousemove = null
    }
  </script>
</body>
</html>